package com.zzzzzz.account.ticket;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.zzzzzz.common.id.UUIDGenerator;
import com.zzzzzz.core.dao.BaseDao;

@Repository
public class TicketDao extends BaseDao{
	
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	private static final String ADD = 						"insert into ticket(ticket_key, ticket_type, class_pk, add_dt) values(?, ?, ?, ?)";
	private static final String DELETE = 					"delete from ticket where ticket_key = ?";
	private static final String FIND_BY_KEY_AND_CATEGORY = 	"select * from ticket where ticket_key = ? and ticket_type = ?";
	
	protected class TicketRowMapper implements RowMapper<Ticket> {
//		@Override
		public Ticket mapRow(ResultSet rs, int rn) throws SQLException {
			Ticket ticket = new Ticket();
			ticket.setKey(rs.getString("ticket_key"));
			ticket.setType(rs.getString("ticket_type"));
			ticket.setClassPK(rs.getLong("class_pk"));
			ticket.setAddDt(rs.getTimestamp("add_dt"));
			return ticket;
		}
	}
	
	public Ticket add(Long classPK, String type) {
		Date now = new Date();

		Ticket ticket = new Ticket();
		ticket.setKey(UUIDGenerator.get());
		ticket.setType(type);
		ticket.setClassPK(classPK);
		ticket.setAddDt(now);
		
		jdbcTemplate.update(ADD, ticket.getKey(), ticket.getType(), ticket.getClassPK(), ticket.getAddDt());
		return ticket;
	}

	public Long findClassPKByKey(String key, String type) throws NoSuchTicketException, ExpiredTicketException {
		Ticket ticket = findByKeyAndType(key, type);
		return ticket.getClassPK();
	}
	
	private Ticket findByKeyAndType(String key, String type) throws NoSuchTicketException, ExpiredTicketException {
		Ticket ticket = jdbcTemplate.queryForObject(FIND_BY_KEY_AND_CATEGORY, new TicketRowMapper(), key, type);
		if(ticket == null){
			throw new NoSuchTicketException(key);
		}else if(isExpired(ticket.getAddDt(), type)){
			throw new ExpiredTicketException(key);
		}
		return ticket;
	}
	
	private boolean isExpired(Date createDate, String type){
		long time = new Date().getTime()-createDate.getTime();
		if(time > 86400000){
			return true;
		}
		return false;
	}

	public void delByKey(String key) throws NoSuchTicketException {
		try{
			jdbcTemplate.update(DELETE, key);
		}catch(Exception e){
			throw new NoSuchTicketException(key);
		}
	}

}